package com.ygqh.baby.controller.utils;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.TemplateHashModel;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DocumentHandler {

    private static Configuration configuration = null;

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_21);
        configuration.setDefaultEncoding("utf-8");
    }

    public static void generateByteArrayOutputStream(String str, OutputStream outStream) throws Exception {
        ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"));

        byte[] data = new byte[1024];

        int count = -1;
        while ((count = is.read(data, 0, 1024)) != -1) {
            outStream.write(data, 0, count);
        }
        data = null;
    }


    //指定要在ftl页面使用的静态包名
    public static TemplateHashModel useStaticPackage(String packageName) {
        try {
            BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
            TemplateHashModel staticModels = wrapper.getStaticModels();
            TemplateHashModel fileStatics = (TemplateHashModel) staticModels
                    .get(packageName);
            return fileStatics;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static byte[] createDocument(byte[] contents, Map<String, Object> dataMap)
            throws Exception {
        ByteArrayOutputStream ba = new ByteArrayOutputStream();

        XLSTransformer transformer = new XLSTransformer();
        InputStream inputStream = new ByteArrayInputStream(contents);
        // 开始填数 ...
        Workbook workbook = transformer.transformXLS(inputStream, dataMap);
        // 其它处理
        Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
        Header header = sheet.getHeader();
        String headerStr = header.getLeft();
        if (StringUtils.isNotEmpty(headerStr)) {
            header.setLeft(ELUtils.evaluate(headerStr, dataMap).toString());
        }
        headerStr = header.getCenter();
        if (StringUtils.isNotEmpty(header.getCenter())) {
            header.setCenter(ELUtils.evaluate(headerStr, dataMap).toString());
        }
        if (StringUtils.isNotEmpty(header.getRight())) {
            header.setRight(ELUtils.evaluate(header.getRight(), dataMap).toString());
        }
        Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());

        //自动行高
        POIUtils.autoRowHeight(activeSheet);
        // 生成字节流
        POIUtils.writeWorkbook(workbook, ba);
        byte[] bytes = ba.toByteArray();
        ba.close();

        return bytes;
    }


    public static void createDownload(byte[] bytes, String fileName, HttpServletRequest request,
                                      HttpServletResponse response) {
        try {

            // 如果想出来让IE提示你是打开还是保存的对话框，加上下面这句就可以了
            String attachmentName = fileName;
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                attachmentName = URLEncoder.encode(attachmentName, "UTF-8");
            } else {
                attachmentName = new String(attachmentName.getBytes("UTF-8"), "ISO8859-1");
            }
            ByteArrayOutputStream ba = new ByteArrayOutputStream();
            ba.write(bytes);
            //response.setHeader("Content-disposition", "attachment; filename=" + attachmentName);  //弹出保存对话框的
            response.setHeader("Content-disposition", "inline; filename=" + attachmentName);//直接打开
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));
            response.setContentLength(ba.size());
            response.setContentType("application/octet-stream");

            ServletOutputStream out = response.getOutputStream();
            ba.writeTo(out);
            out.flush();
            out.close();
            ba.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请使用 ExcelHandle
     *
     * @param uploadFile 上传的文件
     * @return Map
     */
    @Deprecated
    public static Map<Integer, List<Row>> importExcel(MultipartFile uploadFile) {
        if (uploadFile == null) {
            return null;
        }
        Map<Integer, List<Row>> resMap = new HashMap<>();
        try {
            InputStream is = uploadFile.getInputStream();
            Workbook workbook = WorkbookFactory.create(is);
            for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
                Sheet sheetAt = workbook.getSheetAt(numSheet);
                if (sheetAt == null) {
                    continue;
                }
                // Read the Row
                List<Row> rowList = new ArrayList<>(sheetAt.getLastRowNum());
                for (int rowNum = 1; rowNum <= sheetAt.getLastRowNum(); rowNum++) {
                    Row row = sheetAt.getRow(rowNum);
                    rowList.add(row);
                }
                resMap.put(numSheet, rowList);
            }
        } catch (Exception e) {
            throw new RuntimeException("importExcel fail ," + e.getMessage());
        }

        return resMap;
    }

    public static String getCellValue(Cell hssfCell) {
        if (hssfCell == null) {
            return null;
        }
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            DecimalFormat df = new DecimalFormat("0.00");
            String str = df.format(hssfCell.getNumericCellValue());
            // 返回数值类型的值
            return str;
        } else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

    public static void DownloadExcel(byte[] fileTemplate, String fileName, Map<String, Object> dataMap, HttpServletRequest request, HttpServletResponse response) {
        try {

            byte[] bytes = createDocument(fileTemplate, dataMap);
            createDownload(bytes, fileName, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}